package com.jubaozan.service.platform.controller;

import com.jubaozan.c3.framework.utils.ObjectUtil;
import com.jubaozan.c3.framework.utils.ResultHolder;
import com.jubaozan.feign.login.LoginFeignService;
import com.jubaozan.feign.user.UserFeignService;
import com.jubaozan.service.platform.exception.PlatformException;
import com.jubaozan.service.platform.vo.TemplateData;
import com.jubaozan.service.platform.vo.WxMssVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName SendWxMessageController
 * @Description 发送小程序订阅消息Controller
 * @Author SunWei
 * @Version 1.0
 **/
@Api(tags = {"发送小程序订阅消息"}, value = "发送小程序订阅消息")
@RestController
@RequestMapping("/wx")
@Validated
@Slf4j
public class SendWxMessageController {

    private final LoginFeignService loginFeignService;

    public SendWxMessageController(LoginFeignService loginFeignService) {
        this.loginFeignService = loginFeignService;
    }

    @ApiOperation(value = "小程序消息推送")
    @GetMapping("/push")
    public ResultHolder<String> push(String openId,Long storeId){
        ResultHolder<String> accessToken = loginFeignService.getAccessToken("0", storeId);
        if(!accessToken.isSuccess() || ObjectUtil.isEmpty(accessToken)){
            throw new PlatformException("获取accessToken失败");
        }
        RestTemplate restTemplate = new RestTemplate();
        //这里简单起见我们每次都获取最新的access_token（时间开发中，应该在access_token快过期时再重新获取）
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken.getBody();
        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        //用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        wxMssVo.setTouser(openId);
        //订阅消息模板id
        wxMssVo.setTemplate_id("kl74Tt7juV9Gv0J4tF5AJYe2jh5XtDATcj9lrGMxjWc");

        Map<String, TemplateData> m = new HashMap<>(4);
        m.put("thing2", new TemplateData("个体平台入驻审核"));
        m.put("date3", new TemplateData("2020-09-26"));
        m.put("thing18", new TemplateData("平台入驻资料审核"));
        m.put("thing19", new TemplateData("审核完成"));
        wxMssVo.setData(m);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        return ResultHolder.success(responseEntity.getBody());
    }
}
